# -*- coding: UTF-8 -*-

import socket, threading, time, os

SIZE = 1024

def checkExsit(FileName):
    list = os.listdir('.')
    for iterm in list:
        if iterm == FileName:
            os.remove(iterm)
            print 'Exsit file has been removed'
    print 'Create file ...'
    with open(FileName, 'wb') as f: pass

def recvImage(sock, FileName):
    while True:
        data = sock.recv(SIZE)
        if not data:
            break
        else:
            with open(FileName, 'ab') as f:
                f.write(data)
    print 'data received'

def saveImage(sock):
    print 'Begin to save image ...'
    FileName = "%s.jpg" % time.strftime("%Y%m%d%H%M%S")
    checkExsit(FileName)
    t = threading.Thread(target = recvImage, args = (sock, FileName))
    t.setDaemon(True)
    t.start()
    t.join()
    print 'Finished saving image ...'

def tcplink(sock, addr):
    print 'Accept new connection from %s:%s...' % addr
    fromClentData = sock.recv(SIZE)
    print type(fromClentData)

    sock.send('fuck client')
    # if 'fuck' in fromClentData:
    #     sock.send('fuck client')
    # elif 'hello' in fromClentData:
    #     sock.send('hello client')
    # else:
    #     sock.send('what the fuck... client')
    print 'Communication test success'
    while True:
        recv = sock.recv(SIZE)
        # 接收命令
        if recv == 'c':
            print 'receive command'
            cmd = sock.recv(SIZE)
            print 'recv: %s' %cmd
            # 判断命令并执行相应的程序
            recv = None
        # 接收文件（这里主要是图片）
        elif recv == 'f':
            print 'file command'
            saveImage(sock)
            recv = None

# 创建一个socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 监听端口（这里的ip要在不同的情况下更改）
s.bind(('127.0.0.1', 9999))
# 每次只允许一个客户端接入
s.listen(1)
print 'Waiting for connection...'
while True:
    sock, addr = s.accept()
    # 建立一个线程用来监听收到的数据
    t = threading.Thread(target = tcplink, args = (sock, addr))
    # 线程运行
    t.start()
